//
//  M_GoodsByCategoryVC.swift
//  letuofu
//
//  Created by WH-JS on 2019/12/16.
//  Copyright © 2019 WH-JS. All rights reserved.
//

import UIKit
import MJRefresh
import MBProgressHUD

class M_ProductBySearchVC: BaseViewControllerWithHeader,UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout,UITextFieldDelegate {
    lazy var defultView : UIView = {
        let v = UIView()
        v.backgroundColor = .white
        self.safeView.drawView(view: v) { (make) in
            make.left.right.bottom.equalToSuperview()
            make.top.equalTo(toolView.snp.bottom).offset(10)
        }
        let img = v.drawImage(named: "sousuowuxiangguanshangpin_111") { (make) in
            make.centerX.equalToSuperview().offset(20)
            make.centerY.equalToSuperview().offset(-80)
            make.height.width.equalTo(200)
        }
        img.contentMode = .scaleAspectFit
        
        v.drawLabel(text: "搜索无相关商品", fontSize: 19, textColor: .x333333) { (make) in
            make.centerX.equalToSuperview()
            make.top.equalTo(img.snp.bottom).offset(10)
        }.textAlignment = .center
        return v
    }()
    
    var pageIndex = 1
    var pageSize = 100
    var totalSize = 2000
    //商品列表数据
    var productListArr = [[String:Any?]]()
    
    //搜索框
    let searchField = TextField()
    
    let zoneSelBtn = Button()
    var keyword : String
    
    //当前需要的字典数据
    var curzoneCode : ZoneCodeModel
    var cursortCode : ZoneCodeModel?
    var curdirCode : ZoneCodeModel?
    
    //列表控件
    var tableView : QuickTableView<[String:Any?],M_ProductCell>?
    var colltionView : UICollectionView?
    let toolView = UIView()
    //专区列表
    let zoneTableView = QuickTableView<ZoneCodeModel,M_ZoneCell>()
    //专区标识
    var zoneAry = [ZoneCodeModel]()
    
    //排序按钮
    let sortByPrice = sortByButton()
    
    let sortByCount = sortByButton()

    init(keyword: String, zoneCode:ZoneCodeModel) {
        self.keyword = keyword
        self.curzoneCode = zoneCode
        super.init()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        setupUI()
        _sortByPriceButtonClick(button: sortByPrice)
        getZoneCode()
    }
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destination.
        // Pass the selected object to the new view controller.
    }
    */

    func getDataList(zoneCode: String, keyword: String, pageIndex: Int, pageSize: Int, sort: ZoneCodeModel?, dir: ZoneCodeModel?) {
        cursortCode = sort
        let params :[String:Any] = ["identityToken":LocalStorage.getString(forKey: USER_IDENTITYTOKEN) ?? "",
                                    "keyword":keyword,
                                    "zoneCode":zoneCode,
                                    "sort":sort?.code ?? "117002",
                                    "dir":dir?.code ?? "106002",
                                    "pageIndex":pageIndex,
                                    "pageSize":pageSize]
        MBProgressHUD.showOrIncrease()
        API.request(url: .M_SearchAction, params: params) { (result) in
            MBProgressHUD.hideOrDecrease()
            if result.success {
                if let dl = result.data?.getDictionary("data") {
                    for item in dl.getDictList("items") ?? [] {
                     self.productListArr.append(item)
                    }
                 self.pageIndex = dl.getInt("pageIndex") ?? 0
//                 self.pageSize = dl.getInt("pageSize") ?? 0
                 self.totalSize = dl.getInt("totalSize") ?? 0
                }
            }
            self.queryData()
        }
    }
    
    func getZoneCode() {
        if let ary = LocalStorage.getAryToZone(forKey: ZoneCode105) {
            zoneAry = ary
            self.queryZoneData()
            for i in 0...zoneAry.count-1 {
                if zoneAry[i].code == curzoneCode.code {
                    self.zoneTableView.selectRow(at: IndexPath(row: i, section: 0), animated: false, scrollPosition: .top)
                }
            }
        }
        else {
            let popup = PopupSureBox(title: "获取标识失败，请从新登录", sureText: "确定")
            popup.show(vc: UIViewController.topMostController() ?? self)
            popup.onSureButtonClick = {
            }
        }
    }
    
    //重新获取标识来获取数据
    func getListCurCode() {
        self.getDataList(zoneCode: curzoneCode.code, keyword: keyword, pageIndex: pageIndex, pageSize: pageSize,sort: cursortCode, dir: curdirCode)
    }
    
    func addCar(productNo: String) {
        MBProgressHUD.showOrIncrease()
        let params :[String:Any] = ["identityToken":LocalStorage.getString(forKey: USER_IDENTITYTOKEN) ?? "",
                                    "productNo":productNo]
        API.request(url: .M_AddCart, params: params) { (result) in
            MBProgressHUD.hideOrDecrease()
            if result.success {
                let popup = PopupBox(infoText: "成功加入购物车")
                popup.show(vc: UIViewController.topMostController() ?? self)
                
                let noT = NSNotification.Name(rawValue: CAR_CHANGE)
                let dic = ["key":"value"]
                NotificationCenter.default.post(name: noT, object: nil, userInfo:dic)
            }
            else {
                let popup = PopupBox(infoText: result.errMsg ?? "加入购物车失败")
                popup.show(vc: UIViewController.topMostController() ?? self)
            }
        }
    
    }
}


// MARK: UI
extension M_ProductBySearchVC {
    func setupUI() {
        safeView.backgroundColor = .xF2F2F2
        headView.backgroundColor = .white
        
        let searchBG = headView.drawView() { (make) in
            make.left.equalToSuperview().offset(33.5)
            make.centerY.equalTo(backButton)
            make.height.equalTo(25)
            make.right.equalToSuperview().offset(-92.5-14.5)
        }
        searchBG.backgroundColor = .xF2F2F2
        
        searchBG.drawTextField(textField: searchField,placeholder: "搜索您想要的商品", fontSize: 12) { (make) in
            make.centerX.equalToSuperview()
            make.centerY.equalToSuperview()
            make.width.equalToSuperview().offset(-10)
        }
        searchField.text = self.keyword
        searchField.delegate = self
        
        drawRightButton(imageName: "guowuche_21")
        .addTarget(self, action: #selector(_gouwucheButtonClick(button:)), for: .touchUpInside)
        
//        drawRightButton(imageName: "xiaoxi_4")
//        .addTarget(self, action: #selector(_xiaoxiButtonClick(button:)), for: .touchUpInside)
        let newsButton = drawRightButton(imageName: "xiaoxi_4")
        newsButton.addTarget(self, action: #selector(_xiaoxiButtonClick(button:)), for: .touchUpInside)
        UnreadPointForNewsButton(button: newsButton, pointRadius: 3.5,
                                 pointOffset: .init(x: -9.5, y: 10),  color: .xE0551B)

        //画横线
        safeView.drawView { (make) in
            make.left.right.equalToSuperview()
            make.top.equalTo(headView.snp.bottom)
            make.height.equalTo(10)
        }.backgroundColor = .xF2F2F2
        
        safeView.drawView(view: toolView) { (make) in
            make.left.right.equalToSuperview()
            make.top.equalTo(headView.snp.bottom).offset(1)
            make.height.equalTo(40)
        }
        
        var name = ""
        if curzoneCode.code == "105002" {
            name = "京东配送"
        }
        else {
            name = "自营"
        }
        toolView.drawButton(button: zoneSelBtn,title: name, titleColor: .x666666, fontSize: 12) { (make) in
            make.centerY.equalToSuperview()
            make.left.equalToSuperview().offset(30)
        }
        zoneSelBtn.hitEdgInsets = .init(top: -20, left: -20, bottom: -20, right: -20)
        zoneSelBtn.addTarget(self, action: #selector(_onzoneSelAction(button:)), for: .touchUpInside)
        
        toolView.drawImage(named: "lishixiangxia_60") { (make) in
            make.centerY.equalTo(zoneSelBtn.snp.centerY)
            make.left.equalTo(zoneSelBtn.snp.right).offset(5)
        }
        
        toolView.backgroundColor = .white
        toolView.drawButton(button: sortByPrice,title: "积分值", titleColor: .x333333, fontSize: 12) { (make) in
            make.left.equalToSuperview().offset(120)
            make.centerY.equalToSuperview()
        }
        .addTarget(self, action: #selector(_sortByPriceButtonClick(button:)), for: .touchUpInside)
        toolView.drawButton(button: sortByCount,title: "兑换量", titleColor: .x333333, fontSize: 12) { (make) in
            make.centerX.equalToSuperview().offset(50)
            make.centerY.equalToSuperview()
        }
        .addTarget(self, action: #selector(_sortByCountButtonClick(button:)), for: .touchUpInside)
        let btn = toolView.drawButton(imageNamed: "hengpaiban_68") { (make) in
            make.right.equalToSuperview().offset(-20)
            make.centerY.equalToSuperview()
        }
        btn.setImage(UIImage.init(named: "pubuliu_67"), for: .selected)
        btn.addTarget(self, action: #selector(_tableTypeButtonClick(button:)), for: .touchUpInside)
        btn.hitEdgInsets = .init(top: -20, left: -20, bottom: -20, right: -20)
        
        //添加专区列表
        safeView.addSubview(zoneTableView)
        zoneTableView.snp.makeConstraints { (make) in
            make.left.equalToSuperview().offset(28)
            make.top.equalTo(headView.snp.bottom).offset(-8)
            make.width.equalTo(54)
            make.height.equalTo(100)
        }
        // 设置边框
        zoneTableView.layer.borderWidth = 0.5
        zoneTableView.layer.borderColor = UIColor.xF2F2F2.cgColor
        zoneTableView.isHidden = true
        zoneTableView.backgroundColor = .white
                        
        //当点击表格行时
        zoneTableView.onDataSelectedSubject().bindWeak(self) { (data, s) in
            s.onSelectZoneCell(data: data)
        }
        
        //刷新相关事件绑定
        zoneTableView.onSetCellSubject().bindWeak(self) { (cell, s) in
        }

        safeView.drawView { (make) in
            make.left.right.equalToSuperview()
            make.top.equalTo(toolView.snp.bottom)
            make.height.equalTo(1)
        }.backgroundColor = .xF2F2F2

        
        initKeyboardObserver()
        fillAccessoryToolBar()
        
        setupContentUI()
    }
    
    func setupContentUI() {
        tableView?.isHidden = false
        colltionView?.isHidden = true
        if tableView != nil {
            return
        }
        tableView = QuickTableView<[String:Any?],M_ProductCell>()
        safeView.addSubview(tableView!)
        tableView?.snp.makeConstraints { (make) in
            make.left.right.bottom.equalToSuperview()
            make.top.equalTo(toolView.snp.bottom).offset(10)
        }
        safeView.sendSubviewToBack(tableView!)
        tableView?.clipsToBounds = false
        //刷新相关事件绑定
        tableView?.onSetCellSubject().bindWeak(self) { (cell, s) in
            cell.callAddBlock { (dic) in
                self.addCar(productNo: dic.getString("productNo") ?? "")
            }
        }
        
        //当点击表格行时
        tableView?.onDataSelectedSubject().bindWeak(self) { (data, s) in
            s.onSelectCell(data: data)
        }
        
        //当表底上拉刷新更多时
        tableView?.footerLoadMoreSubject.bindWeak(self) { (s) in
            s.getNextPage()
        }
        
        //当表头下拉刷新时
        tableView?.headerRequerySubject.bindWeak(self) { (s) in
            s.refreshall()
            self.tableView?.reloadForHeaderRequery(list: self.productListArr, isLastPage: false)
        }
    }
    
    func setupContentUI2() {
        colltionView?.isHidden = false
        tableView?.isHidden = true
        if colltionView != nil {
            return
        }
        let layout = UICollectionViewFlowLayout()
        layout.sectionInset = .init(top: 5, left: 3, bottom: 5, right: 3)
        colltionView = UICollectionView(frame: .zero, collectionViewLayout: layout)
        //注册一个cell
        colltionView!.register(M_ProductColCell.self, forCellWithReuseIdentifier:"cell")
        //注册一个head
//        colltionView!.register(M_CatalogSubHead.self, forSupplementaryViewOfKind:UICollectionView.elementKindSectionHeader, withReuseIdentifier: "header")
        colltionView?.delegate = self;
        colltionView?.dataSource = self;
        colltionView?.backgroundColor = .xF2F2F2
        //设置每一个cell的宽高
        layout.itemSize = CGSize(width: 173, height: 251)
        safeView.addSubview(colltionView!)
        colltionView?.snp.makeConstraints { (make) in
            make.left.right.bottom.equalToSuperview()
            make.top.equalTo(toolView.snp.bottom).offset(10)
        }
        safeView.sendSubviewToBack(colltionView!)
        colltionView?.clipsToBounds = false
        
        let _ = getRefreshHeader()
        let _ = getRefreshFooter()
    }
    
    class sortByButton : Button {
        let imgUp = UIImageView()
        let imgDown = UIImageView()

        override init(frame: CGRect) {
            super.init(frame: frame)
            //页面设置
            setupUI()
        }
        
        required init?(coder: NSCoder) {
            fatalError("init(coder:) has not been implemented")
        }
        
        func setupUI() {
            drawImage(imageView: imgUp, named: "xiangshang_70") { (make) in
                make.right.equalToSuperview().offset(10)
                make.centerY.equalToSuperview().offset(-5)
            }
            drawImage(imageView: imgDown,named: "xiangxia_69") { (make) in
                make.right.equalToSuperview().offset(10)
                make.centerY.equalToSuperview().offset(5)
            }
        }
    }

        
        func getRefreshHeader()->MJRefreshHeader? {
    //        顶部的下拉初始化
            let header = MJRefreshNormalHeader()
            header.lastUpdatedTimeLabel.isHidden = true
            colltionView?.mj_header = header
            header.setTitle("下拉刷新...", for: .idle)
            header.setTitle("下拉刷新...", for: .pulling)
            header.setTitle("下拉更新中...", for: .refreshing)
            header.setTitle("完成...", for: .willRefresh)
            header.setTitle("下拉刷新...", for: .noMoreData)
            header.setRefreshingTarget(self, refreshingAction: #selector(onHeaderRequery))

    //        顶部的处理逻辑：
            return colltionView?.mj_header
        }
        
        func getRefreshFooter()->MJRefreshFooter? {
            if colltionView?.mj_footer == nil {
                //        底部初始化：
                let footer = MJRefreshAutoNormalFooter()
                footer.isOnlyRefreshPerDrag = true
                colltionView?.mj_footer = footer
                footer.setTitle("", for: .idle)
                footer.setTitle("", for: .pulling)
                footer.setTitle("下拉更新中...", for: .refreshing)
                footer.setTitle("完成...", for: .willRefresh)
                footer.setTitle("", for: .noMoreData)
                footer.setRefreshingTarget(self, refreshingAction: #selector(onFooterLoadMore))
            }

    //        底部处理逻辑：
            if pageIndex * pageSize < totalSize {
                colltionView?.mj_footer.endRefreshing()
            }
            else {
                colltionView?.mj_footer.endRefreshingWithNoMoreData()
            }
            
    //        底部数据加载
             return colltionView?.mj_footer
        }
}

// MARK: event & action
extension M_ProductBySearchVC {
    
    func queryZoneData() {
        zoneTableView.list = zoneAry
        zoneTableView.reloadData()
        zoneTableView.snp.remakeConstraints { (make) in
            make.left.equalToSuperview().offset(20)
            make.top.equalTo(toolView.snp.bottom)
            make.width.equalTo(54)
            make.height.equalTo(30*zoneAry.count)
        }
    }
    
    func queryData() {
        tableView?.list = productListArr
        tableView?.reloadData()
        
        colltionView?.mj_header.endRefreshing()
        colltionView?.mj_footer.endRefreshing()
        colltionView?.reloadData()
        
        if tableView?.list.count == 0 {
            defultView.isHidden = false
        } else {
            defultView.isHidden = true
        }
    }
    
    //重新刷新，删除过滤
    func refreshall() {
        productListArr = []
        getListCurCode()
    }
    
    ///上拉加载更多
    func getNextPage() {
        if pageIndex*pageSize < totalSize {
            self.getDataList(zoneCode: curzoneCode.code, keyword: keyword, pageIndex: pageIndex+1, pageSize: pageSize, sort: cursortCode, dir: curdirCode)
            tableView?.reloadForFooterLoadMore(list: productListArr, isLastPage: false)
        } else {
            tableView?.reloadForFooterLoadMore(list: productListArr, isLastPage: true)
        }
    }
    
    func onSelectCell(data:[String:Any?]){
        let vc = M_ProductDetailVC(info: data)
        pushViewController(vc)
    }
    
    @objc func onHeaderRequery() {
        refreshall()
    }
    
    @objc func onFooterLoadMore() {
        if pageIndex * pageSize < totalSize,productListArr.count > 0 {
            self.getDataList(zoneCode: curzoneCode.code, keyword: keyword, pageIndex: pageIndex+1, pageSize: pageSize, sort: cursortCode, dir: curdirCode)
        }
        else {
            colltionView?.mj_footer.endRefreshingWithNoMoreData()
        }
    }
    
    @objc func _tableTypeButtonClick(button: Button) {
        button.isSelected = !button.isSelected
        if button.isSelected {
            setupContentUI2()
        }
        else {
            setupContentUI()
        }
    }
    
    @objc func _sortByPriceButtonClick(button: Button) {
        sortByCount.imgUp.image = UIImage.init(named: "xiangshang_70")
        sortByCount.imgDown.image = UIImage.init(named: "xiangxia_69")
        sortByCount.setTitleColor(.x333333, for: .normal)
        if let zoneSort = LocalStorage.getAryToZone(forKey: ZoneCode117) {
            for item in zoneSort {
                if item.name.contains("积分") {
                    cursortCode = item
                    break
                }
            }
        }
        
        if let zoneSort = LocalStorage.getAryToZone(forKey: ZoneCode106) {
            for item in zoneSort {
                if !item.code.contains(curdirCode?.code ?? "106002") {
                    curdirCode = item
                    sortByPrice.setTitleColor(.xFC4C02, for: .normal)
                    if curdirCode!.code.contains("106002") {
                        sortByPrice.imgUp.image = UIImage.init(named: "xiangshang_70")
                        sortByPrice.imgDown.image = UIImage.init(named: "hongxiangxia_72")
                    }
                    else {
                        sortByPrice.imgUp.image = UIImage.init(named: "hongxiangshang_71")
                        sortByPrice.imgDown.image = UIImage.init(named: "xiangxia_69")
                    }
                    break
                }
            }
        }
        refreshall()
    }
    
    @objc func _sortByCountButtonClick(button: Button) {
        sortByPrice.imgUp.image = UIImage.init(named: "xiangshang_70")
        sortByPrice.imgDown.image = UIImage.init(named: "xiangxia_69")
        sortByPrice.setTitleColor(.x333333, for: .normal)
        if let zoneSort = LocalStorage.getAryToZone(forKey: ZoneCode117) {
            for item in zoneSort {
                if item.name.contains("兑换量") {
                    cursortCode = item
                    break
                }
            }
        }
        
        if let zoneSort = LocalStorage.getAryToZone(forKey: ZoneCode106) {
            for item in zoneSort {
                if !item.code.contains(curdirCode?.code ?? "106002") {
                    curdirCode = item
                    sortByCount.setTitleColor(.xFC4C02, for: .normal)
                    if curdirCode!.code.contains("106002") {
                        sortByCount.imgUp.image = UIImage.init(named: "xiangshang_70")
                        sortByCount.imgDown.image = UIImage.init(named: "hongxiangxia_72")
                    }
                    else {
                        sortByCount.imgUp.image = UIImage.init(named: "hongxiangshang_71")
                        sortByCount.imgDown.image = UIImage.init(named: "xiangxia_69")
                    }
                    break
                }
            }
        }
        refreshall()
    }
    
    @objc func _onzoneSelAction(button: Button) {
        zoneTableView.isHidden = !zoneTableView.isHidden
        safeView.addSubview(zoneTableView)
    }
    
    @objc func _xiaoxiButtonClick(button: Button) {
        let vc = M_NewsListVC()
        pushViewController(vc)
    }
    
    @objc func _gouwucheButtonClick(button: Button) {
        let vc = M_CartListVC()
        vc.isshowBack = true
        pushViewController(vc)
    }
    
    //当点击表格行事件
    func onSelectZoneCell(data:ZoneCodeModel){
        var name = ""
        if data.code == "105002" {
            name = "京东配送"
        }
        else {
            name = "自营"
        }
        
        zoneSelBtn.setTitle(name, for: .normal)
        zoneTableView.isHidden = true
        curzoneCode = data
        refreshall()
    }
    
    ///collectionView delegate
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let dic = productListArr[indexPath.row]
        onSelectCell(data: dic)
    }
    
    //返回多少个组
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return productListArr.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! M_ProductColCell
        let dic = productListArr[indexPath.row]
        cell.celldata = dic
        cell.callAddBlock {
            self.addCar(productNo: dic.getString("productNo") ?? "")
        }
        return cell
    }
    

    func textFieldShouldReturn(_ textField: UITextField) -> Bool{
        return true
    }
    
    func textFieldDidEndEditing(_ textField: UITextField){
        self.keyword = textField.text ?? ""
        self.productListArr = []
        self.getListCurCode()
    }
}
